package com.example.demo.order.service.impl;

import com.alibaba.cloud.nacos.annotation.NacosConfigListener;
import com.example.demo.order.OrderDto;
import com.example.demo.order.feign.ProductFeignClient;
import com.example.demo.order.service.OrderService;
import com.example.demo.product.ProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ProductFeignClient productFeignClient;

    @Override
    public OrderDto createOrder(String userId, String productId) {

        OrderDto orderDto = new OrderDto();
        orderDto.setOrderId(UUID.randomUUID().toString());
        orderDto.setUserId(userId);
        orderDto.setTotalPrice(null);

        // 使用RestTemplate发送请求
        // ProductDto productDto = restTemplate.getForObject("http://product-service/product/1", ProductDto.class);


        // 使用OpenFeign客户端发送请求
        ProductDto productDto = productFeignClient.getProduct(productId);

        orderDto.setProductList(List.of(productDto));
        orderDto.setTotalPrice(productDto.getProductPrice().multiply(BigDecimal.valueOf(productDto.getProductUnit())));

        return orderDto;
    }

    /**
     * Nacos配置中心监听配置改变
     *
     * @param properties
     */
    @NacosConfigListener(group = "order", dataId = "order-datasource.properties")
    public void configChangeListener(Properties properties) {
        log.info("ConfigChangeListener config:{}", properties.keySet());
        log.info("ConfigChangeListener config:{}", properties.values());
    }
}
